﻿using Face8280WebSocketServer.WebSockt;
using Face8280WebSocketServer.Command;
using DoNetDrive.AspWebSocke.WebSocketServer;
using DoNetDrive.Core;
using DoNetDrive.Core.Command;
using DoNetDrive.Core.Command.Text;
using DotNetty.Buffers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using Face8280WebSocketServer.Interface;
using Face8280WebSocketServer.Command.IPPar;
using Face8280WebSocketServer.Command.WorkParameter;

namespace Face8280WebSocketServer.Controllers
{
    public class WebSocketController : ControllerBase
    {
        static HashSet<string> SystemHttpHeaders = new HashSet<string>() { "Connection", "Host", "Upgrade", "Sec-WebSocket-Version", "Sec-WebSocket-Key" };
        private static ConcurrentDictionary<string, WebSocketServerConnector> WebSocketChannels = new();

        private readonly ILogger<WebSocketController> _logger;
        private IFaceDriveService _DeviceDB;
        public WebSocketController(ILogger<WebSocketController> logger, IFaceDriveService door)
        {
            _logger = logger;
            _DeviceDB = door;
        }
        [HttpGet("/WebSocket")]
        public async Task Get()
        {
            if (HttpContext.WebSockets.IsWebSocketRequest)
            {
                if (HttpContext.Request.Headers.Count > 0)
                {
                    var skeys = HttpContext.Request.Headers.Keys;
                    foreach (var skey in skeys)
                    {
                        if (!SystemHttpHeaders.Contains(skey))
                            Console.WriteLine($"http头：{skey} = {HttpContext.Request.Headers[skey]}");
                    }
                }
                var sn = HttpContext.Request.Headers["SN"];
                if (WebSocketChannels.ContainsKey(sn))
                {
                    WebSocketChannels.Remove(sn, out var val);
                    await val.CloseAsync();
                }
                //获取websocket对象
                using var webSocket = await
                                   HttpContext.WebSockets.AcceptWebSocketAsync();
                //创建websocket客户端详细对象
                var detail = new WebSocketServerClientDetail(HttpContext, sn, webSocket);
                //创建连接通道
                WebSocketServerConnector webSocketConnector = new WebSocketServerConnector(detail);
                //加入到主通道中
                Allocator.AddConnector(sn, webSocketConnector);
                //添加处理管道
              //  webSocketConnector.RemoveRequestHandle(typeof(UDPSerachRequestHandle));
               // webSocketConnector.AddRequestHandle(new UDPSerachRequestHandle());
                //保存管道对象
                WebSocketChannels.TryAdd(sn, webSocketConnector);
                //保存客户端详情对象
                if (Allocator.WebSocketServerClients.ContainsKey(sn))
                {
                    Allocator.WebSocketServerClients.Remove(sn, out _);
                }
                Allocator.WebSocketServerClients.TryAdd(sn, detail);
                var entity = _DeviceDB.GetDBSet();
                var device = entity.FirstOrDefault(a => a.DeviceID.Equals(sn));
                if (device == null)
                {
                   // _DeviceDB.Add
                }
                //开启连接
                await webSocketConnector.ConnectAsync();
                //关闭连接
                await webSocketConnector.CloseAsync();
                //移除管道对象
                WebSocketChannels.Remove(sn, out _);
                //移除客户端详情对象
                Allocator.WebSocketServerClients.Remove(sn, out _);
            }
            else
            {
                HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
            }
        }
        //private async void AddDevice(WebSocketServerClientDetail detail)
        //{
        //    var cmdDetail = Allocator.GetCommandDetail(detail);
        //    JsonCommand cmd = new GetWorkParameter(cmdDetail);
        //    await Allocator.AddCommandAsync(cmd);
        //    var workResult = cmd.getResult() as GetWorkParameterResult;
        //    if (workResult == null && string.IsNullOrWhiteSpace(workResult.JsonValue))
        //    {
        //        var oDevice = new DB.NewModel.Device.FaceDeviceDetailNew
        //        {
        //            DeviceId = detail.Sn,
        //            IPAddress = detail.Host.Host,
        //            Port =(int) detail.Host.Port,
        //            DeviceName = detail.Sn,
        //            Volume = workResult.ResultObj?.Volume,
        //            VoiceMode = workResult.ResultObj?.VoiceMode,
        //            Grettings = workResult.ResultObj?.Grettings,
        //            StrangerVoice = workResult.ResultObj?.StrangerVoice,
        //            Light = workResult.ResultObj?.Light,
        //            Brightness = workResult.ResultObj?.Brightness,
        //            IR = workResult.ResultObj?.IR,
        //            Language = workResult.ResultObj?.Language,
        //            MenuPassword = workResult.ResultObj?.MenuPassword,
        //            Name = workResult.ResultObj?.CompanyName,
        //            QRCodePath = workResult.ResultObj?.QRCodePath,
        //            SaveExternalvisitors = workResult.ResultObj?.SaveExternalvisitors,
        //            SavePhoto = workResult.ResultObj?.SavePhoto,
        //            Bioassay = workResult.ResultObj?.Bioassay,
        //            BioassayThreshold = workResult.ResultObj?.FaceIRThreshold,
        //            Distance = workResult.ResultObj?.Distance,
        //            FaceMask = workResult.ResultObj?.FaceMask,
        //            FaceMaskThreshold = workResult.ResultObj?.FaceComparison,
        //            Door = workResult.ResultObj?.Door,
        //            Free = workResult.ResultObj?.Free,
        //            ReleaseTime = workResult.ResultObj?.ReleaseTime,
        //            Time = workResult.ResultObj?.Time,
        //            Cardbytes = workResult.ResultObj?.Cardbytes,
        //            Exposure = workResult.ResultObj?.Exposure
        //        };
        //        _DeviceDB.AddNew(oDevice);
        //    }
        //    cmd = new GetIPPar(cmdDetail);
        //    await Allocator.AddCommandAsync(cmd);
        //    var ipResult = cmd.getResult() as GetIPParResult;
        //    if (ipResult == null && string.IsNullOrWhiteSpace(ipResult.JsonValue))
        //    {
               
        //    }

        //}
    }
}
